package com.king.oa.view.action;

import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.king.oa.base.BaseAction;
import com.king.oa.domain.Department;
import com.king.oa.util.DepartmentUtil;
import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction<Department> {

	private static final long serialVersionUID = 1L;

	private Long parentId;
	

	/** 列表 */
	public String list() throws Exception {
		List<Department> departmentList = departmentService.findAll();
		
		if(parentId==null){//顶级部门列表
			departmentList = departmentService.findTopList();
		}else{ //子部门列表
			departmentList = departmentService.findChildren(parentId);
			Department parent = departmentService.findById(parentId);
			ActionContext.getContext().put("parent", parent);
		}
		
		ActionContext.getContext().put("departmentList", departmentList);
		return "list";
	}

	/** 删除 */
	public String delete() throws Exception {
		if (departmentService.findById(model.getId()) != null) {
			departmentService.delete(model.getId());
		}
		return "toList";
	}

	/** 添加页面 */
	public String addUI() throws Exception {
		//准备部门列表，departmentList
		List<Department> toList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtil.getAllDepartments(toList);
		
		ActionContext.getContext().put("departmentList", departmentList);
		return "saveUI";
	}

	/** 添加 */
	public String add() throws Exception {
		//封装信息到对象中
		Department parent = departmentService.findById(parentId);
		
		
		model.setParent(parent);
		
		departmentService.save(model);
		return "toList";
	}

	/** 修改页面 */
	public String editUI() throws Exception {
		//准备部门列表，departmentList
		List<Department> toList = departmentService.findTopList();
		List<Department> departmentList = DepartmentUtil.getAllDepartments(toList);
		ActionContext.getContext().put("departmentList", departmentList);
		
		this.model = departmentService.findById(model.getId());
		
		if(this.model.getParent()!=null)	
			this.parentId = this.model.getParent().getId();
		
		return "saveUI";
	}

	/** 修改 */
	public String edit() throws Exception {
		// 1、从数据库获取原对象
		Department department = departmentService.findById(this.model
				.getId());

		// 2、设置新数据
		department.setName(this.model.getName());
		department.setDescription(this.model.getDescription());
		department.setParent(departmentService.findById(parentId));//设置隶属上级部门
		
		// 3、更新到数据库
		departmentService.update(department);
		
		return "toList";
	}

	public Long getParentId() {
		return parentId;
	}

	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}

}
